/*----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the 
License at http://www.mozilla.org/MPL/
	
Software distributed under the License is distributed on 
an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, 
either express or implied. 
See the License for the specific language governing rights and 
limitations under the License.
	
The Original Code is Fever RS ( ActionScript 3 ) Framework code.
	
The Initial Developer of the Original Code is Romain Ecarnot.
Portions created by Initial Developer are Copyright (C) 2006
the Initial Developer. All Rights Reserved.
	
Contributor(s):
	
Unless required by applicable law or agreed to in writing, 
software distributed under the License is distributed on 
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
OF ANY KIND, either express or implied.
See the License for the specific language governing permissions 
and limitations under the License.
----------------------------------------------------------------------------*/

package fever.load.strategy 
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	
	import com.bourre.load.Loader;
	import com.bourre.load.strategy.LoadStrategy;
	
	import fever.data.crypto.Cipher;
	import fever.log.FeverDebug;
	import fever.utils.Stringifier;	

	/**
	 * Loading strategy for encrypted data.
	 * 
	 * @see fever.load.CipherFileLoader	 * @see fever.load.CipherXMLLoader
	 * 
	 * @author Romain Ecarnot
	 */
	public class CipherLoaderStrategy implements LoadStrategy
	{
		//--------------------------------------------------------------------
		// Private properties
		//--------------------------------------------------------------------

		private var _owner : Loader;
		private var _loader : URLLoader;
		private var _algo : Class;		private var _secretKey : String;
		private var _bytesLoaded : uint;
		private var _bytesTotal : uint;

		
		//--------------------------------------------------------------------
		// Public API
		//--------------------------------------------------------------------
		
		/**
		 * Constructor.
		 * 
		 * @param cryptAlgo Algorithm to use for decrypting loaded data
		 * @param secretKey Secret key to use for decrypting loaded data
		 * 
		 * @see fever.data.crypto.Cipher
		 * @see fever.data.crypto.CryptAlgorithm
		 */
		public function CipherLoaderStrategy( cryptAlgo : Class, secretKey : String )
		{
			_algo = cryptAlgo;
			_secretKey = secretKey;
			
			_bytesLoaded = 0;
			_bytesTotal = 0;
		}
		
		/**
		 * Loads <code>request</code> in <code>context</code>.
		 */
		public function load( request : URLRequest = null, context : LoaderContext = null ) : void
		{
			_loader = new URLLoader( );
			_loader.addEventListener( ProgressEvent.PROGRESS, _onProgress );
			_loader.addEventListener( Event.COMPLETE, _onComplete );
			_loader.addEventListener( Event.OPEN, _onOpen );
			_loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, _onSecurityError );
			_loader.addEventListener( HTTPStatusEvent.HTTP_STATUS, _onHttpStatus );
			_loader.addEventListener( IOErrorEvent.IO_ERROR, _onIOError );
			
			if ( context != null ) FeverDebug.WARN( this + ".load() doesn't " + 
				"support LoaderContext argument." ); 
			
			_loader.load( request );
		}

		/**
		 * Returns loaded bytes.
		 */
		public function getBytesLoaded() : uint
		{
			return _bytesLoaded;
		}

		/**
		 * Returns total bytes to load
		 */
		public function getBytesTotal() : uint
		{
			return _bytesTotal;
		}

		/**
		 * Sets the loader owner.
		 * 
		 * @param owner Loader event
		 */
		public function setOwner( owner : Loader ) : void
		{
			_owner = owner;
		}

		/**
		 * Release loader.
		 */
		public function release() : void
		{
			if ( _loader ) _loader.close( );
		}

		/**
		 * Returns the string representation of this instance.
		 */
		public function toString() : String 
		{
			return Stringifier.parse( this );
		}

		
		//--------------------------------------------------------------------
		// Private implementations
		//--------------------------------------------------------------------
		
		/** @private */
		protected function _onProgress( e : ProgressEvent ) : void
		{
			_bytesLoaded = e.bytesLoaded;
			_bytesTotal = e.bytesTotal;
			
			if ( _owner ) _owner.fireOnLoadProgressEvent( );
		}
		
		/** @private */
		protected function _onComplete( e : Event ) : void 
		{
			if ( _owner ) 
			{
				_owner.setContent( 
					Cipher.getInstance( _algo ).decrypt( 
						_loader.data as String, _secretKey 
					) 
				);
				_owner.fireOnLoadInitEvent( );
			}
		}
		
		/** @private */
		protected function _onOpen( event : Event ) : void
		{
			if ( _owner ) _owner.fireOnLoadStartEvent( );
		}
		
		/** @private */
		protected function _onSecurityError( e : SecurityErrorEvent ) : void 
		{
			if ( _owner ) _owner.fireOnLoadErrorEvent( e.text );
		}
		
		/** @private */
		protected function _onHttpStatus( e : HTTPStatusEvent ) : void 
		{
			var status : int = e.status;
			var s : String;
			
			if( status < 100 ) s = "internalError";
			else if( status < 200 ) s = "informational";
			else if( status < 300 ) s = "";
			else if( status < 400 ) s = "redirection";
			else if( status < 500 ) s = "clientError";
			else if( status < 600 ) s = "serverError";
     		
     		if( s.length > 0 )
     		{
				if ( _owner ) _owner.fireOnLoadErrorEvent( s );
     		}
		}
		
		/** @private */
		protected function _onIOError( e : IOErrorEvent ) : void 
		{
			if ( _owner ) _owner.fireOnLoadErrorEvent( e.text );
		}
	}
}
